package com.supcalls.service;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

@Component
public class ZookeeperDistributedLock {

    private final CuratorFramework client;
    private final String LOCK_PATH = "/locks/";

    public ZookeeperDistributedLock(CuratorFramework client) {
        this.client = client;
    }

    public boolean acquireLock(String key, long time, TimeUnit unit) {
        InterProcessMutex lock = new InterProcessMutex(client, LOCK_PATH + key);
        try {
            return lock.acquire(time, unit); // 尝试获取锁
        } catch (Exception e) {
            throw new RuntimeException("获取锁失败", e);
        }
    }

    public void releaseLock(String key) {
        InterProcessMutex lock = new InterProcessMutex(client, LOCK_PATH + key);
        try {
            lock.release(); // 释放锁
        } catch (Exception e) {
            throw new RuntimeException("释放锁失败", e);
        }
    }
}
